package com.comboo.example.web.controller;

import com.comboo.example.domain.Person;
import com.comboo.example.web.api.RequestPageWrapper;
import com.comboo.example.web.api.RequestWrapper;
import com.comboo.example.web.api.ResponsePageWrapper;
import com.comboo.example.web.api.ResponseWrapper;
import com.comboo.example.web.applicationService.PersonApplicationService;
import com.comboo.example.web.command.PersonCreateCommand;
import com.comboo.example.web.command.PersonUpdateCommand;
import com.comboo.example.web.exception.ErrorType;
import com.comboo.example.web.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Sherman
 * created in 2018/12/19 2018
 */
@Api(tags = "个人中心")
@RestController
public class PersonController {

    private final PersonApplicationService personApplicationService;

    @Autowired
    public PersonController(PersonApplicationService personApplicationService) {
        this.personApplicationService = personApplicationService;
    }

    @ApiOperation("查询个人信息")
    @GetMapping("/person/{id}")
    public ResponseWrapper<Person> get(@PathVariable Long id) {
        Person person = personApplicationService.get(id);
        if (person == null) {
            throw new ServiceException(ErrorType.DATA_ACCESS_ERROR);
        }
        return ResponseWrapper.success(personApplicationService.get(id));
    }

    @ApiOperation("创建个人信息")
    @PostMapping("/person")
    public ResponseWrapper<Person> create(@Validated @RequestBody RequestWrapper<PersonCreateCommand> req) {
        return ResponseWrapper.success(personApplicationService.create(req.getPayload()));
    }

    @ApiOperation("更新个人信息")
    @PutMapping("/person")
    public ResponseWrapper<Person> update(@Validated @RequestBody PersonUpdateCommand command) {
        return ResponseWrapper.success(personApplicationService.update(command));
    }

    @ApiOperation("查询所有人信息")
    @PostMapping("/persons")
    public ResponseWrapper<List<Person>> findPage(@Validated @RequestBody RequestPageWrapper req) {
        return ResponsePageWrapper.success(personApplicationService.findPage(req.getPageable()));
    }

    @ApiOperation("删除个人信息")
    @DeleteMapping("/person/{id}")
    public ResponseWrapper<Void> delete(@PathVariable Long id) {
        personApplicationService.delete(id);
        return ResponseWrapper.ok();
    }

}
